import axios from 'axios';

import ajax from "m/ajax/ajaxPost.js"

const dMember = require('../../models/dict/dMember');
const config = require('../../models/dict/config');


import { bus } from '../../models/comm/bus.js';
const Vue = require('vue');

const yz = require('../../models/comm/yz');

export default {

    data() {
        return {
            sysUserName: "",
            sysUserAvatar: "",
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: ''
            },
            menuArray: [],
            me: {},
            topMenuArray: [],
            leftMenuArray: [],
            currentView: require('./404.vue'),
            leftId: "0",
            topId: "0",
            company: {}
        }
    },
    methods: {
        sel1() {

            console.log("点击了顶层菜单");
        },
        onSubmit() {
            console.log('submit!');
        },
        handleopen() {
            //console.log('handleopen');
        },
        handleclose() {
            //console.log('handleclose');
        },
        handleselect: function (a, b, c) {

            console.log(a);
            console.log(b);
             
        },
        //退出登录
        logout: function () {
            var _this = this;
            this.$confirm('确认退出吗?', '提示', {
                //type: 'warning'
            }).then(() => {
                sessionStorage.removeItem('member');
                _this.$router.push('/login');
            }).catch(() => {

            });


        },
        getMe() {

            var _this = this
            axios.post("/a", {
                class: "member",
                para: "getMe",
                j: {
                    menuIdArray: true
                }
            }).then((res) => {



                console.log("Home.vue  找出用户来了!");
                var member = dMember.fmtMember(res.data.info)
                this.me = member;

                this.getMyCompany();
                this.$bus.on('getMyInfo', () => {

                    return this.me
                })
                sessionStorage.memberId = member._id
                sessionStorage.name = member.name
                sessionStorage.picUrl = member.picUrl
                var menuIdArray = res.data.menuIdArray
                if (!sessionStorage.member) {
                    window.location.href = "/login"
                }

                localStorage.companyCode = "1999";
                this.sysUserName = sessionStorage.name;
                this.sysUserAvatar = sessionStorage.picUrl;

                var routes = this.$router.options.routes

                this.menuArray = memberMenu(routes, menuIdArray)
                this.topMenuArray = [];
                this.menuArray.forEach(function (menu, index) {



                    this.topMenuArray.push(menu);

                }, this);
                this.PageLoad();

                RongIMLib.RongIMClient.init(config.rongAppKey);
                RongIMLib.RongIMClient.setConnectionStatusListener({
                    onChanged: function (status) {
                        switch (status) {
                            case RongIMLib.ConnectionStatus.CONNECTED:
                                console.log('链接成功');
                                break;
                            case RongIMLib.ConnectionStatus.CONNECTING:
                                console.log('正在链接');
                                break;
                            case RongIMLib.ConnectionStatus.DISCONNECTED:
                                console.log('断开连接');
                                break;
                            case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
                                console.log('其他设备登录');
                                break;
                            case RongIMLib.ConnectionStatus.DOMAIN_INCORRECT:
                                console.log('域名不正确');
                                break;
                            case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
                                console.log('网络不可用');
                                break;
                        }
                    }
                });



                // 消息监听器
                RongIMLib.RongIMClient.setOnReceiveMessageListener({
                    // 接收到的消息
                    onReceived: function (message) {
                        // 判断消息类型
                        console.log(message.content.content);
                        _this.notify(message)
                    }
                });
                RongIMClient.connect(member.rongToken, {
                    onSuccess: function (userId) {
                        console.log("Login successfully." + userId);
                    },
                    onTokenIncorrect: function () {
                        console.log('token无效');
                    },
                    onError: function (errorCode) {
                        var info = '';
                        switch (errorCode) {
                            case RongIMLib.ErrorCode.TIMEOUT:
                                info = '超时';
                                break;
                            case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                                info = '未知错误';
                                break;
                            case RongIMLib.ErrorCode.UNACCEPTABLE_PaROTOCOL_VERSION:
                                info = '不可接受的协议版本';
                                break;
                            case RongIMLib.ErrorCode.IDENTIFIER_REJECTED:
                                info = 'appkey不正确';
                                break;
                            case RongIMLib.ErrorCode.SERVER_UNAVAILABLE:
                                info = '服务器不可用';
                                break;
                        }
                        console.log(errorCode);
                    }
                });
            });



        },
        notify(message) {
            var type = "info";
            var duration = 0;  //毫秒
            if (message.content.extra.type) {
                type = message.content.extra.type
            }

            if (message.content.extra.duration) {
                duration = message.content.extra.duration
            }

            this.$notify({
                title: '消息提醒',
                message: message.content.content,
                duration: duration,
                type: type
            });


            if (message.content.extra.event == "countMe") {
                this.countMe()
            }

        },
        countMe() {
            axios.post("/a", {
                class: "member",
                para: "countMe",
                j: {
                    menuIdArray: true
                }
            }).then((res) => {
                if (res.data.re == "ok") {
                    this.me.newTaskNum = res.data.newTaskNum
                }
                else {
                    this.$message.error(res.data.errMsg)
                }

            })
        },
        test() {
            console.log("在home执行");
        },
        selTop(index) {


            this.topMenuArray.forEach(function (menu) {
                if (menu.id == index) {
                    this.leftMenuArray = menu.children

                    if (this.leftMenuArray.length > 0) {

                        var menu2 = yz.clone(this.leftMenuArray[0])

                        var menu3 = null
                        if (menu2.children) {
                            if (menu2.children.length > 0) {
                                menu3 = menu2.children[0]
                            }
                        }

                        this.selLeft(menu3)


                    }




                    return false
                }
            }, this);


        },
        selLeft(menu) {
            if (!menu) {
                return
            }
            // this.currentView = item.component;
            // console.log(item);

            var path = '/#' + menu.path

            window.location.href = path;
            this.PageLoad()


            // this.leftMenuArray.forEach(function (leftMenu) {
            //     if (leftMenu.children) {
            //         leftMenu.children.forEach(function (leftCld) {
            //             if (leftCld.id = menu.id) {
            //                 this.leftId = menu.id
            //             }
            //         }, this);
            //     }

            // }, this);
        },
        PageLoad() {

            this.menuArray.forEach(function (menu1) {

                if (menu1.children) {
                    menu1.children.forEach(function (menu2) {


                        if (menu2.children) {
                            menu2.children.forEach(function (menu3) {
                                if ("#" + menu3.path.toLowerCase() == window.location.hash.toLocaleLowerCase()) {

                                    this.leftMenuArray = menu1.children;

                                    this.$nextTick(function () {
                                        // DOM 更新了
                                        this.topId = menu1.id

                                        this.leftId = menu3.id
                                    })


                                }
                            }, this);
                        }
                    }, this);
                }

            }, this);

        },
        getMyCompany() {

            ajax.post({
                class: "company",
                para: "getCompany",
                j: {
                    code: this.me.companyCode
                },
                fun: (res) => {
                    if (res.data.err) {
                        this.$message({
                            showClose: true,
                            message: res.data.err,
                            type: 'error'
                        });
                    }
                    else {
                        this.company = res.data.info
                    }

                }

            })


        }

    },
    mounted() {



        this.getMe()
        /*注释内容*/
        this.$bus.on('countMe', (msg) => {
            this.countMe()
        })


    }

}

function memberMenu(routes, menuIdArray) {

    routes.forEach(function (menu) {

        var has = false;

        menuIdArray.forEach(function (menuId) {
            if (menu.id == menuId) {
                has = true
                return false
            }
        }, this);

        if (!has) {
            menu.hidden = true
        }

        if (menu.children) {
            menu.children = memberMenu(menu.children, menuIdArray)
        }

    }, this);
    return routes
}
